<template>
  <div class="container mx-auto">
    <h1 class="my-8 text-4xl font-bold">Список пользователей</h1>
    <div class="flex justify-between mb-8">
      <AppInput
        v-model="filterQuery"
        placeholder="ФИО"
        label="Фильтр по ФИО"
      />
      <AppButton @click="handleUser"> Добавить пользователя</AppButton>
    </div>
    <AppLoader
      class="mx-auto"
      v-if="pending"
    />
    <div
      v-else-if="error"
      class="bg-red-200 rounded text-red-500 p-4"
    >
      {{ error }}
    </div>
    <div v-else>
      <AppTable
        :users="data.users"
        @sort-by="sort"
      />
    </div>
    <AppPagination
      :pages="pagesCount"
      @set-page="setPage"
    />
  </div>
</template>

<script setup lang="ts">
  const { getUsers } = useApi();

  const page = ref(1);
  const perPage = ref(10);
  const filterQuery = ref();
  const sortBy = ref();
  const asc = ref(false);

  const { data, pending, error } = await getUsers(
    filterQuery,
    sortBy,
    asc,
    page,
    perPage
  );

  const pagesCount = computed(() =>
    Math.floor(data.value.total / perPage.value)
  );

  const setPage = (_page: number) => {
    page.value = _page;
  };

  const sort = (_sortBy: string) => {
    sortBy.value = _sortBy;
    asc.value = !asc.value;
  };
  const router = useRouter();

  const handleUser = () => {
    router.push(`/0?edit`);
  };
</script>

<style scoped></style>
